package com.yami.shop.service.impl;


import cn.hutool.json.JSONObject;
import com.yami.shop.common.bean.Wechat;
import com.yami.shop.service.WechatService;
import com.yami.shop.service.utils.PayRequest;
import com.yami.shop.service.utils.PayResponse;
import com.yami.shop.service.utils.WeChatPayHelper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
public class WechatServiceImpl implements WechatService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WeChatPayHelper weChatPayHelper;

    @Autowired
    private  Wechat wechat;

    private String url="https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public String getMinProgramOpenId(String code) {
        String requestUrl=url+"?grant_type=authorization_code&appid="+wechat.getAppid()+"&secret="+wechat.getSecret()+"&js_code="+code;
        ResponseEntity<String> res = restTemplate.exchange(requestUrl, HttpMethod.GET, null, String.class);
        String responseJson=res.getBody();
        JSONObject jsonObject= new JSONObject(responseJson);
        String openid=jsonObject.getStr("openid");
        return openid;
    }

    @Override
    public PayResponse payment(PayRequest payRequest) {
        String jsapiPay=weChatPayHelper.getJSAPIPay(payRequest);
        PayResponse res=weChatPayHelper.getMinPay(jsapiPay);
        return res;
    }


}
